package com.jxpanda.commons.signature;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;

@Slf4j
public class Signature {

    public static byte[] signature(String content, PrivateKey privateKey, SignatureAlgorithm algorithm) {
        try {
            java.security.Signature signature = java.security.Signature.getInstance(algorithm.getValue());
            signature.initSign(privateKey);
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            return signature.sign();
        } catch (Exception ex) {
            log.error("[SIGN ERROR]", ex);
        }
        return new byte[0];
    }


    public static boolean verify(String content, byte[] sign, PublicKey publicKey, SignatureAlgorithm algorithm) {
        try {
            java.security.Signature signature = java.security.Signature.getInstance(algorithm.getValue());
            signature.initVerify(publicKey);
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            return signature.verify(sign);
        } catch (Exception ex) {
            log.error("[VERIFY ERROR]", ex);
        }
        return false;
    }

}
